<!-- index.html - 主界面 -->
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>用户主界面 - 待办事项管理系统</title>
    <link rel="stylesheet" href="css/navbar.css">
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: 'Microsoft YaHei', Arial, sans-serif;
            background: #f8f9fa;
            min-height: 100vh;
        }
        
        .main-content {
            max-width: 1200px;
            margin: 30px auto;
            padding: 0 20px;
        }
        
        .dashboard {
            display: grid;
            grid-template-columns: 1fr 1fr 1fr;
            gap: 20px;
            margin-bottom: 30px;
        }
        
        .stat-card {
            background: white;
            padding: 25px;
            border-radius: 10px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            text-align: center;
        }
        
        .stat-number {
            font-size: 36px;
            font-weight: bold;
            color: #667eea;
            margin-bottom: 10px;
        }
        
        .stat-label {
            color: #666;
            font-size: 14px;
        }
        
        .todo-section {
            background: white;
            border-radius: 10px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            overflow: hidden;
        }
        
        .todo-header {
            background: #f8f9fa;
            padding: 20px;
            border-bottom: 1px solid #e9ecef;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        
        .todo-header h2 {
            color: #333;
            font-size: 20px;
        }
        
        .add-todo-btn {
            background: #667eea;
            color: white;
            border: none;
            padding: 10px 20px;
            border-radius: 5px;
            cursor: pointer;
            font-weight: 500;
            transition: background 0.3s ease;
        }
        
        .add-todo-btn:hover {
            background: #5a6fd8;
        }
        
        .todo-filters {
            padding: 20px;
            border-bottom: 1px solid #e9ecef;
            display: flex;
            gap: 15px;
            align-items: center;
            flex-wrap: wrap;
        }
        
        .filter-group {
            display: flex;
            align-items: center;
            gap: 8px;
        }
        
        .filter-group label {
            font-weight: 500;
            color: #333;
        }
        
        .filter-group select,
        .filter-group input {
            padding: 8px 12px;
            border: 1px solid #ddd;
            border-radius: 5px;
            font-size: 14px;
        }
        
        .search-input {
            min-width: 200px;
        }
        
        .todo-list {
            padding: 20px;
        }
        
        .todo-item {
            background: #f8f9fa;
            border: 1px solid #e9ecef;
            border-radius: 8px;
            padding: 15px;
            margin-bottom: 15px;
            transition: all 0.3s ease;
        }
        
        .todo-item:hover {
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
        }
        
        .todo-item.completed {
            background: #d4edda;
            border-color: #c3e6cb;
        }
        
        .todo-header-row {
            display: flex;
            justify-content: space-between;
            align-items: flex-start;
            margin-bottom: 10px;
        }
        
        .todo-title {
            font-weight: 600;
            color: #333;
            font-size: 16px;
            flex: 1;
        }
        
        .todo-actions {
            display: flex;
            gap: 8px;
        }
        
        .action-btn {
            padding: 5px 10px;
            border: none;
            border-radius: 3px;
            cursor: pointer;
            font-size: 12px;
            transition: all 0.3s ease;
        }
        
        .edit-btn {
            background: #ffc107;
            color: #212529;
        }
        
        .delete-btn {
            background: #dc3545;
            color: white;
        }
        
        .complete-btn {
            background: #28a745;
            color: white;
        }
        
        .detail-btn {
            background: #17a2b8;
            color: white;
        }
        
        .todo-content {
            color: #666;
            margin-bottom: 10px;
            line-height: 1.5;
        }
        
        .todo-meta {
            display: flex;
            justify-content: space-between;
            align-items: center;
            font-size: 12px;
            color: #888;
        }
        
        .todo-times {
            display: flex;
            gap: 15px;
        }
        
        .todo-status {
            padding: 4px 8px;
            border-radius: 3px;
            font-weight: 500;
        }
        
        .status-completed {
            background: #d4edda;
            color: #155724;
        }
        
        .status-pending {
            background: #fff3cd;
            color: #856404;
        }
        
        .countdown {
            font-weight: 600;
        }
        
        .countdown-urgent {
            color: #dc3545;
        }
        
        .countdown-overdue {
            color: #dc3545;
        }
        
        .countdown-completed {
            color: #28a745;
        }
        
        .empty-state {
            text-align: center;
            padding: 40px;
            color: #666;
        }
        
        .empty-state h3 {
            margin-bottom: 10px;
            color: #333;
        }
        
        /* 模态框样式 */
        .modal {
            display: none;
            position: fixed;
            z-index: 1000;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0,0,0,0.5);
        }
        
        .modal-content {
            background-color: white;
            margin: 5% auto;
            padding: 30px;
            border-radius: 10px;
            width: 90%;
            max-width: 500px;
            position: relative;
        }
        
        .close {
            position: absolute;
            right: 20px;
            top: 15px;
            font-size: 28px;
            font-weight: bold;
            cursor: pointer;
            color: #aaa;
        }
        
        .close:hover {
            color: #000;
        }
        
        .modal h2 {
            margin-bottom: 20px;
            color: #333;
        }
        
        .form-group {
            margin-bottom: 20px;
        }
        
        .form-group label {
            display: block;
            margin-bottom: 8px;
            font-weight: 500;
            color: #333;
        }
        
        .form-group input,
        .form-group textarea,
        .form-group select {
            width: 100%;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 5px;
            font-size: 14px;
        }
        
        .form-group textarea {
            resize: vertical;
            min-height: 100px;
        }
        
        .modal-buttons {
            display: flex;
            gap: 10px;
            justify-content: flex-end;
            margin-top: 20px;
        }
        
        .btn {
            padding: 10px 20px;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            font-weight: 500;
            transition: background 0.3s ease;
        }
        
        .btn-primary {
            background: #667eea;
            color: white;
        }
        
        .btn-secondary {
            background: #6c757d;
            color: white;
        }
        
        .btn:hover {
            opacity: 0.9;
        }
        
        @media (max-width: 768px) {
            .dashboard {
                grid-template-columns: 1fr;
            }
            
            .todo-filters {
                flex-direction: column;
                align-items: stretch;
            }
            
            .filter-group {
                flex-direction: column;
                align-items: stretch;
            }
            
            .todo-header-row {
                flex-direction: column;
                gap: 10px;
            }
            
            .todo-actions {
                justify-content: flex-start;
            }
            
            .todo-meta {
                flex-direction: column;
                align-items: flex-start;
                gap: 10px;
            }
            
            .todo-times {
                flex-direction: column;
                gap: 5px;
            }
        }
    </style>
</head>
<body>
    <!-- 统一导航栏 -->
    <nav class="navbar">
        <div class="navbar-content">
            <a href="home.html" class="navbar-brand">
                <span class="brand-icon">🏠</span>
                <h1>待办事项管理系统</h1>
            </a>
            
            <ul class="navbar-nav">
                <li class="nav-item">
                    <a href="home.html" class="nav-link">
                        <span class="nav-icon">🏠</span>
                        首页
                    </a>
                </li>
                <li class="nav-item">
                    <a href="user_index.html" class="nav-link active">
                        <span class="nav-icon">📋</span>
                        待办事项
                    </a>
                </li>
                <li class="nav-item">
                    <a href="profile.html" class="nav-link">
                        <span class="nav-icon">👤</span>
                        个人信息
                    </a>
                </li>
            </ul>
            
            <div class="user-section">
                <div class="user-info">
                    <div class="user-avatar" id="userAvatar">U</div>
                    <span class="user-name" id="userName">用户</span>
                </div>
                <button class="logout-btn" id="logoutBtn">
                    <span>🚪</span>
                    退出登录
                </button>
            </div>
        </div>
    </nav>

    <div class="main-content">
        <div class="dashboard">
            <div class="stat-card">
                <div class="stat-number" id="totalTodos">0</div>
                <div class="stat-label">总待办事项</div>
            </div>
            <div class="stat-card">
                <div class="stat-number" id="completedTodos">0</div>
                <div class="stat-label">已完成</div>
            </div>
            <div class="stat-card">
                <div class="stat-number" id="pendingTodos">0</div>
                <div class="stat-label">进行中</div>
            </div>
        </div>

        <div class="todo-section">
            <div class="todo-header">
                <h2>我的待办事项</h2>
                <button class="add-todo-btn" onclick="openAddModal()">添加待办事项</button>
            </div>
            
            <div class="todo-filters">
                <div class="filter-group">
                    <label for="categoryFilter">分类:</label>
                    <select id="categoryFilter" onchange="filterTodos()">
                        <option value="">全部分类</option>
                        <option value="生活">生活</option>
                        <option value="娱乐">娱乐</option>
                        <option value="学习">学习</option>
                        <option value="游戏">游戏</option>
                    </select>
                </div>
                
                <div class="filter-group">
                    <label for="statusFilter">状态:</label>
                    <select id="statusFilter" onchange="filterTodos()">
                        <option value="">全部状态</option>
                        <option value="未完成">未完成</option>
                        <option value="进行中">进行中</option>
                        <option value="已完成">已完成</option>
                    </select>
                </div>
                
                <div class="filter-group">
                    <label for="searchInput">搜索:</label>
                    <input type="text" id="searchInput" class="search-input" placeholder="搜索待办事项..." oninput="filterTodos()">
                </div>
            </div>
            
            <div class="todo-list" id="todoList">
                <!-- 待办事项列表将在这里动态生成 -->
            </div>
        </div>
    </div>

    <!-- 添加/编辑待办事项模态框 -->
    <div id="todoModal" class="modal">
        <div class="modal-content">
            <span class="close" onclick="closeModal()">&times;</span>
            <h2 id="modalTitle">添加待办事项</h2>
            <form id="todoForm">
                <div class="form-group">
                    <label for="todoTitle">标题</label>
                    <input type="text" id="todoTitle" required>
                </div>
                <div class="form-group">
                    <label for="todoContent">内容</label>
                    <textarea id="todoContent" required></textarea>
                </div>
                <div class="form-group">
                    <label for="todoStatus">状态</label>
                    <select id="todoStatus" required>
                        <option value="未完成">未完成</option>
                        <option value="进行中">进行中</option>
                        <option value="已完成">已完成</option>
                    </select>
                </div>
                <div class="form-group">
                    <label for="todoDueDate">截止日期</label>
                    <input type="datetime-local" id="todoDueDate" required>
                </div>
                <div class="modal-buttons">
                    <button type="button" class="btn btn-secondary" onclick="closeModal()">取消</button>
                    <button type="submit" class="btn btn-primary">保存</button>
                </div>
            </form>
        </div>
    </div>

    <!-- 新增：详情弹窗 HTML -->
    <div id="todoDetailModal" class="modal">
        <div class="modal-content" style="max-width: 400px;">
            <span class="close" onclick="closeDetailModal()">&times;</span>
            <h2 id="detailTitle" style="margin-bottom: 10px;"></h2>
            <div style="margin-bottom: 10px; color: #666;" id="detailContent"></div>
            <div style="margin-bottom: 10px;"><b>状态：</b><span id="detailStatus"></span></div>
            <div style="margin-bottom: 10px;"><b>创建时间：</b><span id="detailCreateTime"></span></div>
            <div style="margin-bottom: 10px;"><b>截止时间：</b><span id="detailDueDate"></span></div>
            <div style="margin-bottom: 10px;"><b>倒计时：</b><span id="detailCountdown" class="countdown"></span></div>
            <div style="text-align: right;"><button class="btn btn-secondary" onclick="closeDetailModal()">关闭</button></div>
        </div>
    </div>

    <script src="js/navbar.js"></script>
    <script>
        let todos = [];
        let editingTodoId = null;
        // 新增：详情弹窗相关变量
        let detailTimer = null;
        let currentDetailTodo = null;
        // 新增：全局倒计时定时器
        let listCountdownTimer = null;

        // 页面加载时初始化
        document.addEventListener('DOMContentLoaded', function() {
            // 导航栏已经通过navbar.js初始化
            loadTodos();
            
            // 检查是否需要打开添加模态框
            const openAddModal = localStorage.getItem('openAddModal');
            if (openAddModal === 'true') {
                localStorage.removeItem('openAddModal'); // 清除参数
                setTimeout(() => openAddModal(), 500); // 延迟打开，确保页面加载完成
            }
        });

        async function loadTodos() {
            const currentUser = window.navbar.getCurrentUser();
            if (!currentUser || !currentUser.userId) {
                console.error('用户未登录或用户ID无效');
                return;
            }
            
            try {
                const response = await fetch(`/api/todos/user/${currentUser.userId}`);
                if (response.ok) {
                    todos = await response.json();
                    updateDashboard();
                    renderTodos();
                } else {
                    console.error('加载待办事项失败');
                }
            } catch (error) {
                console.error('加载待办事项错误:', error);
            }
        }

        function updateDashboard() {
            const total = todos.length;
            const completed = todos.filter(todo => todo.status === '已完成').length;
            const pending = total - completed;
            
            document.getElementById('totalTodos').textContent = total;
            document.getElementById('completedTodos').textContent = completed;
            document.getElementById('pendingTodos').textContent = pending;
        }

        function renderTodos() {
            const todoList = document.getElementById('todoList');
            const categoryFilter = document.getElementById('categoryFilter').value;
            const statusFilter = document.getElementById('statusFilter').value;
            const searchTerm = document.getElementById('searchInput').value.toLowerCase();
            
            let filteredTodos = todos;
            
            // 新增：如果 localStorage.selectedCategory 存在，优先只显示该分类
            const selectedCategory = localStorage.getItem('selectedCategory');
            if (selectedCategory) {
                filteredTodos = filteredTodos.filter(todo => getTodoCategory(todo) === selectedCategory);
                // 自动设置分类筛选框
                if (categoryFilter === '') {
                    document.getElementById('categoryFilter').value = selectedCategory;
                }
                // 用完后清除，避免影响下次
                localStorage.removeItem('selectedCategory');
            }
            
            // 分类筛选
            if (categoryFilter) {
                filteredTodos = filteredTodos.filter(todo => {
                    const category = getTodoCategory(todo);
                    return category === categoryFilter;
                });
            }
            
            // 状态筛选
            if (statusFilter) {
                filteredTodos = filteredTodos.filter(todo => todo.status === statusFilter);
            }
            
            // 搜索筛选
            if (searchTerm) {
                filteredTodos = filteredTodos.filter(todo => 
                    todo.title.toLowerCase().includes(searchTerm) ||
                    todo.content.toLowerCase().includes(searchTerm)
                );
            }
            
            if (filteredTodos.length === 0) {
                todoList.innerHTML = `
                    <div class="empty-state">
                        <h3>暂无待办事项</h3>
                        <p>点击"添加待办事项"开始创建您的第一个任务</p>
                    </div>
                `;
                // 清除倒计时定时器
                if (listCountdownTimer) clearInterval(listCountdownTimer);
                listCountdownTimer = null;
                return;
            }
            
            todoList.innerHTML = filteredTodos.map(todo => {
                const createTime = new Date(todo.createTime);
                const dueDate = new Date(todo.dueDate);
                // 这里不再直接计算倒计时文本，改为渲染 data-todo-id
                return `
                    <div class="todo-item ${todo.status === '已完成' ? 'completed' : ''}">
                        <div class="todo-header-row">
                            <div class="todo-title">${todo.title}</div>
                            <div class="todo-actions">
                                <button class="action-btn detail-btn" onclick="showTodoDetail(${todo.todoId})">详情</button>
                                <button class="action-btn edit-btn" onclick="editTodo(${todo.todoId})">编辑</button>
                                <button class="action-btn delete-btn" onclick="deleteTodo(${todo.todoId})">删除</button>
                                ${todo.status === '未完成' ? 
                                    `<button class="action-btn complete-btn" onclick="completeTodo(${todo.todoId})">完成</button>` : 
                                    ''
                                }
                            </div>
                        </div>
                        <div class="todo-content">${todo.content}</div>
                        <div class="todo-meta">
                            <div class="todo-times">
                                <span>创建: ${createTime.toLocaleString()}</span>
                                <span>截止: ${dueDate.toLocaleString()}</span>
                                <span class="countdown" data-todo-id="${todo.todoId}"></span>
                            </div>
                            <span class="todo-status ${todo.status === '已完成' ? 'status-completed' : 'status-pending'}">
                                ${todo.status}
                            </span>
                        </div>
                    </div>
                `;
            }).join('');
            // 渲染后启动倒计时定时器
            if (listCountdownTimer) clearInterval(listCountdownTimer);
            updateListCountdowns();
            listCountdownTimer = setInterval(updateListCountdowns, 1000);
        }

        function updateListCountdowns() {
            todos.forEach(todo => {
                const elem = document.querySelector(`.countdown[data-todo-id='${todo.todoId}']`);
                if (!elem) return;
                const now = new Date();
                const dueDate = new Date(todo.dueDate);
                let countdownText = '';
                let countdownClass = '';
                const timeLeft = dueDate - now;
                if (todo.status === '已完成') {
                    countdownText = '已完成';
                    countdownClass = 'countdown-completed';
                } else if (timeLeft < 0) {
                    const absTimeLeft = Math.abs(timeLeft);
                    const days = Math.floor(absTimeLeft / (24 * 60 * 60 * 1000));
                    const hours = Math.floor((absTimeLeft % (24 * 60 * 60 * 1000)) / (60 * 60 * 1000));
                    const minutes = Math.floor((absTimeLeft % (60 * 60 * 1000)) / (60 * 1000));
                    const seconds = Math.floor((absTimeLeft % (60 * 1000)) / 1000);
                    countdownText = `逾期 ${days}天${hours}小时${minutes}分${seconds}秒`;
                    countdownClass = 'countdown-overdue';
                } else if (timeLeft < 24 * 60 * 60 * 1000) {
                    const hours = Math.floor(timeLeft / (60 * 60 * 1000));
                    const minutes = Math.floor((timeLeft % (60 * 60 * 1000)) / (60 * 1000));
                    const seconds = Math.floor((timeLeft % (60 * 1000)) / 1000);
                    countdownText = `剩余 ${hours}小时${minutes}分${seconds}秒`;
                    countdownClass = 'countdown-urgent';
                } else {
                    const days = Math.floor(timeLeft / (24 * 60 * 60 * 1000));
                    const hours = Math.floor((timeLeft % (24 * 60 * 60 * 1000)) / (60 * 60 * 1000));
                    const minutes = Math.floor((timeLeft % (60 * 60 * 1000)) / (60 * 1000));
                    const seconds = Math.floor((timeLeft % (60 * 1000)) / 1000);
                    countdownText = `剩余 ${days}天${hours}小时${minutes}分${seconds}秒`;
                    countdownClass = 'countdown-normal';
                }
                elem.textContent = countdownText;
                elem.className = 'countdown ' + countdownClass;
            });
        }

        function filterTodos() {
            renderTodos();
        }

        // 根据待办事项内容判断分类
        function getTodoCategory(todo) {
            const title = todo.title.toLowerCase();
            const content = todo.content ? todo.content.toLowerCase() : '';
            const text = title + ' ' + content;

            // 生活类关键词
            if (text.includes('家务') || text.includes('打扫') || text.includes('洗衣服') || 
                text.includes('做饭') || text.includes('购物') || text.includes('买菜') ||
                text.includes('健康') || text.includes('运动') || text.includes('锻炼') ||
                text.includes('医院') || text.includes('体检') || text.includes('生活')) {
                return '生活';
            }
            
            // 娱乐类关键词
            if (text.includes('电影') || text.includes('电视剧') || text.includes('音乐') ||
                text.includes('旅行') || text.includes('旅游') || text.includes('聚会') ||
                text.includes('娱乐') || text.includes('休闲') || text.includes('放松')) {
                return '娱乐';
            }
            
            // 学习类关键词
            if (text.includes('学习') || text.includes('读书') || text.includes('课程') ||
                text.includes('考试') || text.includes('作业') || text.includes('复习') ||
                text.includes('技能') || text.includes('培训') || text.includes('知识')) {
                return '学习';
            }
            
            // 游戏类关键词
            if (text.includes('游戏') || text.includes('打游戏') || text.includes('攻略') ||
                text.includes('成就') || text.includes('等级') || text.includes('副本')) {
                return '游戏';
            }

            // 默认分类为生活
            return '生活';
        }

        function openAddModal() {
            editingTodoId = null;
            document.getElementById('modalTitle').textContent = '添加待办事项';
            document.getElementById('todoForm').reset();
            
            // 设置默认截止时间为明天
            const tomorrow = new Date();
            tomorrow.setDate(tomorrow.getDate() + 1);
            document.getElementById('todoDueDate').value = tomorrow.toISOString().slice(0, 16);
            
            document.getElementById('todoModal').style.display = 'block';
        }

        function closeModal() {
            document.getElementById('todoModal').style.display = 'none';
            editingTodoId = null;
        }

        function editTodo(todoId) {
            const todo = todos.find(t => t.todoId === todoId);
            if (!todo) return;
            
            editingTodoId = todoId;
            document.getElementById('modalTitle').textContent = '编辑待办事项';
            document.getElementById('todoTitle').value = todo.title;
            document.getElementById('todoContent').value = todo.content;
            document.getElementById('todoStatus').value = todo.status;
            
            // 格式化日期时间
            const dueDate = new Date(todo.dueDate);
            document.getElementById('todoDueDate').value = dueDate.toISOString().slice(0, 16);
            
            document.getElementById('todoModal').style.display = 'block';
        }

        function showTodoDetail(todoId) {
            const todo = todos.find(t => t.todoId === todoId);
            if (!todo) return;
            currentDetailTodo = todo;
            // 设置弹窗内容
            document.getElementById('detailTitle').textContent = todo.title;
            document.getElementById('detailContent').textContent = todo.content;
            document.getElementById('detailStatus').textContent = todo.status;
            document.getElementById('detailCreateTime').textContent = new Date(todo.createTime).toLocaleString();
            document.getElementById('detailDueDate').textContent = new Date(todo.dueDate).toLocaleString();
            updateDetailCountdown();
            document.getElementById('todoDetailModal').style.display = 'block';
            // 启动倒计时定时器
            if (detailTimer) clearInterval(detailTimer);
            detailTimer = setInterval(updateDetailCountdown, 1000);
        }

        function closeDetailModal() {
            document.getElementById('todoDetailModal').style.display = 'none';
            if (detailTimer) clearInterval(detailTimer);
            detailTimer = null;
            currentDetailTodo = null;
        }

        function updateDetailCountdown() {
            if (!currentDetailTodo) return;
            const now = new Date();
            const dueDate = new Date(currentDetailTodo.dueDate);
            let countdownText = '';
            let countdownClass = '';
            const timeLeft = dueDate - now;
            if (currentDetailTodo.status === '已完成') {
                countdownText = '已完成';
                countdownClass = 'countdown-completed';
            } else if (timeLeft < 0) {
                const absTimeLeft = Math.abs(timeLeft);
                const days = Math.floor(absTimeLeft / (24 * 60 * 60 * 1000));
                const hours = Math.floor((absTimeLeft % (24 * 60 * 60 * 1000)) / (60 * 60 * 1000));
                const minutes = Math.floor((absTimeLeft % (60 * 60 * 1000)) / (60 * 1000));
                const seconds = Math.floor((absTimeLeft % (60 * 1000)) / 1000);
                countdownText = `逾期 ${days}天${hours}小时${minutes}分${seconds}秒`;
                countdownClass = 'countdown-overdue';
            } else if (timeLeft < 24 * 60 * 60 * 1000) {
                const hours = Math.floor(timeLeft / (60 * 60 * 1000));
                const minutes = Math.floor((timeLeft % (60 * 60 * 1000)) / (60 * 1000));
                const seconds = Math.floor((timeLeft % (60 * 1000)) / 1000);
                countdownText = `剩余 ${hours}小时${minutes}分${seconds}秒`;
                countdownClass = 'countdown-urgent';
            } else {
                const days = Math.floor(timeLeft / (24 * 60 * 60 * 1000));
                const hours = Math.floor((timeLeft % (24 * 60 * 60 * 1000)) / (60 * 60 * 1000));
                const minutes = Math.floor((timeLeft % (60 * 60 * 1000)) / (60 * 1000));
                const seconds = Math.floor((timeLeft % (60 * 1000)) / 1000);
                countdownText = `剩余 ${days}天${hours}小时${minutes}分${seconds}秒`;
                countdownClass = 'countdown-normal';
            }
            const countdownElem = document.getElementById('detailCountdown');
            countdownElem.textContent = countdownText;
            countdownElem.className = 'countdown ' + countdownClass;
        }

        async function deleteTodo(todoId) {
            if (!confirm('确定要删除这个待办事项吗？')) return;
            
            try {
                const response = await fetch(`/api/todos/${todoId}`, {
                    method: 'DELETE'
                });
                
                if (response.ok) {
                    todos = todos.filter(t => t.todoId !== todoId);
                    updateDashboard();
                    renderTodos();
                } else {
                    alert('删除失败');
                }
            } catch (error) {
                console.error('删除错误:', error);
                alert('删除失败');
            }
        }

        async function completeTodo(todoId) {
            try {
                const todo = todos.find(t => t.todoId === todoId);
                if (!todo) return;
                
                const response = await fetch(`/api/todos/${todoId}`, {
                    method: 'PUT',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        ...todo,
                        status: '已完成'
                    })
                });
                
                if (response.ok) {
                    todo.status = '已完成';
                    updateDashboard();
                    renderTodos();
                } else {
                    alert('更新失败');
                }
            } catch (error) {
                console.error('更新错误:', error);
                alert('更新失败');
            }
        }

        // 表单提交处理
        document.getElementById('todoForm').addEventListener('submit', async function(e) {
            e.preventDefault();
            
            const currentUser = window.navbar.getCurrentUser();
            if (!currentUser || !currentUser.userId) {
                alert('用户未登录');
                return;
            }
            
            const formData = {
                title: document.getElementById('todoTitle').value,
                content: document.getElementById('todoContent').value,
                status: document.getElementById('todoStatus').value,
                dueDate: document.getElementById('todoDueDate').value,
                userId: currentUser.userId
            };
            
            try {
                let response;
                if (editingTodoId) {
                    // 编辑现有待办事项
                    const existingTodo = todos.find(t => t.todoId === editingTodoId);
                    if (!existingTodo) return;
                    
                    response = await fetch(`/api/todos/${editingTodoId}`, {
                        method: 'PUT',
                        headers: {
                            'Content-Type': 'application/json'
                        },
                        body: JSON.stringify({
                            ...existingTodo,
                            ...formData
                        })
                    });
                } else {
                    // 添加新待办事项
                    response = await fetch('/api/todos', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json'
                        },
                        body: JSON.stringify(formData)
                    });
                }
                
                if (response.ok) {
                    closeModal();
                    loadTodos(); // 重新加载数据
                } else {
                    alert('保存失败');
                }
            } catch (error) {
                console.error('保存错误:', error);
                alert('保存失败');
            }
        });

        // 点击模态框外部关闭
        window.onclick = function(event) {
            const modal = document.getElementById('todoModal');
            if (event.target === modal) {
                closeModal();
            }
        }
    </script>
</body>
</html>

